package hu.kami.twobears;

import hu.kami.twobears.techemptests.JSONTests;

import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLDecoder;

import org.armedbear.lisp.Interpreter;
import org.glassfish.grizzly.http.server.HttpServer;

public class NodeABCL {

	private final String[] startupscripts = {"/lisp/twobears/startup.lisp"};

	public int run (String[] args) {
		int res = 0;

		try {

			Interpreter interpreter = Interpreter.getInstance();
			if (interpreter == null ) {
				interpreter = Interpreter.createInstance();
			}

			// http://stackoverflow.com/questions/320542/how-to-get-the-path-of-a-running-jar-file
			String path = NodeABCL.class.getProtectionDomain().getCodeSource().getLocation().getPath();
			String decodedPath = URLDecoder.decode(path, "UTF-8");
			System.err.println("Running as " + decodedPath);
			
			interpreter.eval("(setf *twobears-jar-path* \""+ decodedPath.substring(1) + "\")");
			
			ClassLoader c = ClassLoader.getSystemClassLoader();   
			URL[] urls = ((URLClassLoader)c).getURLs();
			System.err.println("Classpath:");
			for(URL url: urls){
				System.err.println(url.getFile());
			}
			
			// load essential lisp functions
			for (String script : startupscripts) {
				if(getClass().getResource(script) != null) {
					Utils.loadFromClasspath(script);
				} else {
					throw new RuntimeException("Startupscript " + script + " not found on classpath!");
				}	
			}

			HttpServer server = HttpServer.createSimpleServer();

			JSONTests.addTestHandlers(server);
			
			server.start();
			System.out.println("Press any key to stop...");
			System.in.read();
		} catch (Exception e) {
			System.err.println(e);
			res = 1;
		}

		return res;
	}

	public static void main(String[] args) {
		System.exit(new NodeABCL().run(args));
	}
}
